package com.kordar.api.modular.unicomJS;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kordar.api.modular.unicomJS.entity.OrderTmp;
import com.kordar.api.modular.unicomJS.mapper.OrderMapper;
import com.kordar.api.modular.unicomJS.service.OrderService;
import com.kordar.api.util.JwtTokenUtil;
import com.kordar.api.util.Response;
import com.kordar.api.util.ResponseUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("unicomjs")
public class ZOPController {

    private final RestTemplate restTemplate;
    private final OrderService orderService;

    // 选号...
    @PostMapping("choice-number")
    public Response<Object> choiceNumber(@Validated ZOPChoiceNumberRequestImpl numberRequest) {
        JSONObject body = ZOPUtil.send(restTemplate, numberRequest);
        return ResponseUtil.success(ZOPUtil.getData(body));
    }

    @PostMapping("customer-auth")
    public Response<Object> customerAuth(@Validated ZOPCheckAuthRequestImpl zopAuthRequest) {
        JSONObject body = ZOPUtil.send(restTemplate, zopAuthRequest);
        JSONObject data = ZOPUtil.getData(body);
        // 先判断aCode不等于0000就报错，报错语可用aDesc;后判断bCode不等于0000也报错，报错语可用bDesc；
        // （两个返回编码先后校验顺序没明确要求）；如果两个编码都是0000，就代表成功
        String aCode = data.getString("aCode");
        if (!aCode.equals("0000")) {
            return ResponseUtil.error(1, data.getString("aDesc"));
        }
        String bCode = data.getString("bCode");
        if (!bCode.equals("0000")) {
            return ResponseUtil.error(1, data.getString("bDesc"));
        }
        return ResponseUtil.success();
    }

    // 号码选占
    @PostMapping("number-status")
    public Response<Object> numberStatus(@Validated ZOPNumberStatusRequestImpl numberStatusRequest) {
        JSONObject body = ZOPUtil.send(restTemplate, numberStatusRequest);
        JSONObject data = ZOPUtil.getData(body);
        String rspCode = data.getString("rspCode");
        if (!rspCode.equals("0000")) {
            return ResponseUtil.error(1, data.getString("rspDesc"));
        }

        return ResponseUtil.success();
    }

    // 预提交
    @PostMapping("pre-order")
    public Response<Object> perOrder(@Validated ZOPPreOrderRequestImpl preOrderRequest) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String number = "ML_" + sdf.format(new Date()) + ZOPUtil.getRandomString(8);
        preOrderRequest.setNumber(number);
        JSONObject body = ZOPUtil.send(restTemplate, preOrderRequest);
        JSONObject data = ZOPUtil.getData(body);
        String rspCode = data.getString("rspCode");
        if (!rspCode.equals("0000")) {
            return ResponseUtil.error(1, data.getString("rspDesc"));
        }

        JSONObject obj = JSONObject.parseObject((data.getString("body")));
        obj.put("orderId", number);

        if (!orderService.tmpOrder(preOrderRequest, obj.getString("orderNo"))) {
            return ResponseUtil.error(1, "系统异常，下单失败");
        }


        return ResponseUtil.success(obj);
    }

    @PostMapping("submit-order")
    public Response<Object> submitOrder(@Validated ZOPSubmitRequestImpl submitRequest) {

        OrderTmp orderTmp = null;
        if ((orderTmp = orderService.existTmpOrder(submitRequest.getThirdOrderId())) == null) {
            return ResponseUtil.error(1, "提交的订单不存在!");
        }
        submitRequest.setGoodsId(submitRequest.getProvinceCode() + submitRequest.getGoodsId().substring(2));
        JSONObject body = ZOPUtil.send(restTemplate, submitRequest);
        JSONObject data = ZOPUtil.getData(body);
        String rspCode = data.getString("rspCode");
        if (!rspCode.equals("0000")) {
            return ResponseUtil.error(1, data.getString("rspDesc"));
        }
        JSONObject obj = JSONObject.parseObject((data.getString("body")));
        if (!orderService.updateOrder(
                submitRequest,
                orderTmp,
                data.getString("uuid"),
                obj.getString("orderNo"),
                obj.getString("perNumber"),
                obj.getString("shortUrl")
        )) {
            return ResponseUtil.error(1, "系统异常，下单失败");
        }

        return ResponseUtil.success(obj);
    }

    @PostMapping("token")
    public Response<Object> token() {
        String token = JwtTokenUtil.generateToken("unicomjs",
                new Date(System.currentTimeMillis() + 86400 * 1000), null);
        JSONObject object = new JSONObject();
        object.put("token", token);
        return ResponseUtil.success(object);
    }


}
